package com.seocoo.worker.base.multiImage;

import com.seocoo.worker.base.LuBanFactory;
import com.seocoo.worker.base.http.BaseRsp;
import com.seocoo.worker.base.http.DWBaseRequest;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.http.HttpMediaType;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class ReqUploadFiles extends DWBaseRequest<BaseRsp<RspImage>> {
    File file;

    public ReqUploadFiles(File file) {

        super("/api/openapi/upload");
        this.mediaType = HttpMediaType.MEDIA_TYPE_MULTIPART_FORM;
        this.file = file;
    }

    @Override
    public Object buildParam() {
        try
        {
            File newFile = new File(AppCacheManager.getFileCache(), this.getFileName(file.getName()));
            newFile =  LuBanFactory.compress(file,newFile, 1024);
            if (newFile != null && newFile.exists()){
                file  = newFile;
            }
        }catch (Exception e){

        }
        return super.buildParam();
    }


    /***
     * 创建文件名
     * @return
     */
    private final String getFileName(String name) {

        // 文件类型
        int separatorIndex = name.lastIndexOf(".");
        String suffix = (separatorIndex < 0) ? "" : name.substring(separatorIndex);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String date = format.format(new Date());
        //文件类型前缀 + 用户ID + 时间 + 随机数 + 文件类型
        return  date + getRandom() + suffix;
    }
    /**
     * 生成文件名随机数
     *
     * @return
     */
    private final static String getRandom() {

        Random random = new Random();
        StringBuffer randomBf = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            randomBf.append(random.nextInt(9));
        }
        return randomBf.toString();
    }
}
